<template>
  <div class="app-container" style="padding: 0;">
    <el-row style="height: 100%;">
      <!--部门数据-->
      <el-col :span="4" :xs="24" :style="{ backgroundImage: variables.menuBackground }" class="dept">
        <div class="head-container">
          <div style="height: 42px;padding-top: 10px;font-weight: bold;">
            <span>工厂列表</span>
          </div>
          <!-- <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          /> -->
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="true"
            :filter-node-method="filterNode" ref="tree" node-key="id" accordion highlight-current
            @node-click="handleNodeClick" class="tree">
            <template #default="{ node, data }">
              <div :style="{ fontSize: node.level == 1 ? '14px' : '12px' }"
                style="padding:0 20px 0 15px;text-align: left">
                {{ node.label }}
              </div>
            </template>
          </el-tree>
        </div>
      </el-col>
      <!--设备数据-->
      <el-col :span="20" :xs="24"
        style="height: 100%;" class="top-title-border">
        <el-row :gutter="10" style="padding:6px 0 0 0;margin: 0;" class="top-title-background">
          <el-col :span="19" style="height: 34px;">
            <el-tag size="mini" class="tag">{{ currentTopNode.label }}</el-tag>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width=""
              style="display: inline-block;position: relative;top:-14px">
              <el-form-item label="" prop="name">
                <el-input v-model="queryParams.name" placeholder="设备名称" clearable style="width: 160px"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="" prop="industryType">
                <el-select v-model="queryParams.industryType" placeholder="所属行业" style="width: 160px" clearable>
                  <el-option v-for="dict in dict.type.oil_industry_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="deviceType">
                <el-select v-model="queryParams.deviceType" placeholder="机组类型" style="width: 160px" clearable>
                  <el-option v-for="type in typeOptions" :key="type.id" :label="type.typeName"
                    :value="type.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="onLine">
                <el-select v-model="queryParams.onLine" placeholder="是否在线" style="width: 160px" clearable>
                  <el-option v-for="dict in dict.type.oil_yes_no" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <i class="el-icon-search" @click="handleQuery" style="color: #C9C9C9;cursor: pointer;"></i>
                <!-- <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" class="button" size="mini" @click="handleAdd"
              v-hasPermi="['oil:device:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
        <el-button
          class="button"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oil:device:edit']"
        >修改</el-button>
      </el-col> -->
          <el-col :span="1.5">
            <el-button type="primary" class="button" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['oil:device:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" class="button" size="mini" @click="handleExport"
              v-hasPermi="['oil:device:export']">导出</el-button>
          </el-col>
          <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>

        <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="id" width="55" />
          <el-table-column label="设备名称" align="center" prop="name" />
          <el-table-column label="铭牌编号" align="center" prop="code" />
          <el-table-column label="所属工厂" align="center" prop="deptName" />
          <el-table-column label="油品编号" align="center" prop="oilCode">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.oil_code" :value="scope.row.oilCode" />
            </template>
          </el-table-column>
          <el-table-column label="所属行业" align="center" prop="industryType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.oil_industry_type" :value="scope.row.industryType" />
            </template>
          </el-table-column>
          <el-table-column label="机组类型" align="center" prop="deviceTypeName">
          </el-table-column>
          <el-table-column label="区域编号" align="center" prop="addressCode" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="100">
            <!-- <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
            </template> -->
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updateTime" width="100">
            <!-- <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateDate, '{y}-{m}-{d}') }}</span>
            </template> -->
          </el-table-column>
          <el-table-column label="设备状态" align="center" prop="stateName" />
          <el-table-column label="是否在线" align="center" prop="onLine">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.oil_yes_no" :value="scope.row.onLine" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['oil:device:edit']">设置</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditVariable(scope.row)"
                v-hasPermi="['oil:device:edit']">监测指标</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['oil:device:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改设备管理对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="40%">
      <el-form ref="form" :model="form" :rules="rules" label-width="10px">
        <el-row class="info-title">基础信息</el-row>
        <el-row style="padding-left: 10px;" :gutter="40">
          <el-col :span="8">
            <div class="info-label">设备名称</div>
            <el-form-item label="" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="info-label">铭牌编号</div>
            <el-form-item label="" prop="code">
              <el-input v-model="form.code" placeholder="请输入铭牌编号" :disabled="form.id"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="info-label">油品编号</div>
            <el-form-item label="" prop="oilCode">
              <el-select v-model="form.oilCode" placeholder="油品编号">
                <el-option v-for="dict in dict.type.oil_code" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="info-label">所属行业</div>
            <el-form-item label="" prop="industryType">
              <el-select v-model="form.industryType" placeholder="请选择所属行业">
                <el-option v-for="dict in dict.type.oil_industry_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="info-label">机组类型</div>
            <el-form-item label="" prop="deviceType">
              <el-select v-model="form.deviceType" placeholder="请选择机组类型">
                <el-option v-for="item in typeOptions" :key="item.id" :label="item.typeName"
                  :value="parseInt(item.id)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="info-label">区域编号</div>
            <el-form-item label="" prop="addressCode">
              <el-input v-model="form.addressCode" placeholder="请输入区域编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="info-title">数采模块
          <div style="float: right;">
            <span style="font-size: 14px;font-weight: bold;margin-right: 15px;" :style="{color:form.connect?'green':'grey'}">{{ form.connect?"在线":"离线" }}</span>
            <el-button class="action-button" size="mini" @click="startDriver(form.code)">开启</el-button>
            <el-button class="action-button" size="mini" @click="stopDriver(form.code)">关闭</el-button>
          </div>
        </el-row>
        <el-row style="padding-left: 10px;" :gutter="40">
           <el-col :span="8">
            <div class="info-label">采集协议</div>
            <el-form-item label="" prop="driverName">
              <el-select v-model="form.driverName" placeholder="请选择采集协议" @change="driverChange">
                <el-option v-for="dict in dict.type.oil_driver" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="info-label">数采模块ip</div>
            <el-form-item label="" prop="ip">
              <el-input v-model="form.ip" placeholder="请输入数采模块ip" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="info-label">数采模块端口号</div>
            <el-form-item label="" prop="port">
              <el-input v-model="form.port" placeholder="请输入数采模块端口号" />
            </el-form-item>
          </el-col>
          <div v-if="form.driverName === 'MQTTDriver'" style="width: 100%;">
           <el-col :span="8">
            <div class="info-label">MQTT用户名</div>
            <el-form-item label="" prop="username">
              <el-input v-model="form.username" placeholder="请输入MQTT用户名" />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <div class="info-label">MQTT密码</div>
            <el-form-item label="" prop="password">
              <el-input v-model="form.password" placeholder="请输入MQTT密码" type="password" show-password />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <div class="info-label">上传主题</div>
            <el-form-item label="" prop="topic">
              <el-input v-model="form.topic" placeholder="请输入上传主题" />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <div class="info-label">MQTT客户端Id</div>
            <el-form-item label="" prop="clientId">
              <el-input v-model="form.clientId" placeholder="请输入MQTT客户端Id" />
            </el-form-item>
          </el-col>
          </div>
        </el-row>
        <!-- <el-form-item label="创建时间" prop="createDate">
          <el-date-picker clearable v-model="form.createDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updateDate">
          <el-date-picker clearable v-model="form.updateDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否在线" prop="onLine">
          <el-select v-model="form.onLine" placeholder="请选择是否在线">
            <el-option v-for="dict in dict.type.oil_yes_no" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-row class="info-title">归属工厂</el-row>
          <el-form-item prop="deptId">
            <treeselect v-model="form.deptId" :options="deptOptions" placeholder="请选择归属工厂" :show-count="true"/>
          </el-form-item>
        <el-row class="info-title">传感器</el-row>
        <el-form-item label="">
          <el-checkbox-group v-model="form.sensorIds">
            <el-checkbox v-for="item in sensorOptions" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-row class="info-title">备注</el-row>
        <el-form-item prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="form.driverName === 'MQTTDriver'?1:5" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button class="footer-button" @click="submitForm">确 定</el-button>
        <el-button class="footer-button" @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import variables from "@/assets/styles/variables.scss";
import { listDevice, getDevice, delDevice, addDevice, updateDevice, startDriverByDevice, stopDriverByDevice, getConnectState } from "@/api/oil/device";
import { listSensor } from "@/api/oil/sensor";
import { deptTreeSelect } from "@/api/system/user";
import { listType } from "@/api/oil/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Device",
  dicts: ['oil_device_type', 'oil_industry_type', 'oil_code', 'oil_yes_no', 'oil_driver'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        industryType: null,
        deviceType: null,
        deptId: null,
        state: null,
        onLine: null,
      },
      // 表单参数
      form: {
        sensorIds:[],
        deptId:"",
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "设备铭牌编号不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属工厂不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "blur" }
        ],
        ip: [
          { required: true, message: "数采模块IP不能为空", trigger: "blur" }
        ],
        port: [
          { required: true, message: "数采模块端口号不能为空", trigger: "blur" }
        ],
      },
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      //当前选中一级节点
      currentTopNode: { label: "全部" },
      sensorOptions: [],
      typeOptions:[]
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getSensors();
    this.getTypes();
  },
  computed: {
    variables() {
      return variables;
    },
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    getTypes(){
      listType({pageSize:5000}).then(res=>{
        this.typeOptions = res.rows;
      })
    },
    getSensors() {
      listSensor({ pageSize: 5000 }).then(res => {
        this.sensorOptions = res.rows
      })
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
      const currentNode = this.$refs.tree.getNode(data);
      // 获取顶级父节点
      let parentNode = currentNode;
      // console.log(currentNode);
      // while (parentNode.level > 1) {
      //   parentNode = parentNode.$parent;
      // }
      this.currentTopNode = parentNode;
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        oilCode: null,
        industryType: null,
        deviceType: null,
        addressCode: null,
        ip: null,
        port: null,
        deptId: null,
        createBy: null,
        createDate: null,
        updateBy: null,
        updateDate: null,
        state: null,
        onLine: null,
        remark: null,
        sensorIds: [],
        connect:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.form.sensorIds = this.form.sensorIds!=undefined ? this.form.sensorIds.split(",").map(Number) : [];
        console.log(this.form.sensorIds);
        this.getConnectState(this.form.code);
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sensorIds = this.form.sensorIds.join(",");
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.onLine = 0;
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备编号为"' + ids + '"的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oil/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    handleEditVariable(row){
      const deviceId = row.id;
      this.$router.push("/device/edit-variable/index/" + deviceId);
    },
    /** 启动采集程序 */
    startDriver(code) {
      startDriverByDevice(code).then(response => {
        this.$modal.msgSuccess("采集程序已启动");
        this.cancel();
      });
    },
    /** 停止采集程序 */
    stopDriver(code) {
      stopDriverByDevice(code).then(response => {
        this.$modal.msgSuccess("采集程序已停止");
        this.cancel();
      });
    },
    /** 获取设备连接状态 */
    async getConnectState(code) {
       getConnectState(code).then(response => {
        if (response.data) {
          this.$set(this.form, 'connect', true);
        } else {
          this.$set(this.form, 'connect', false);
        }
        console.log(this.form.connect);
      });
    },
    driverChange() {
      if (this.form.driverName === 'MQTTDriver') {
        this.$set(this.form, 'ip', '127.0.0.1');
        this.$set(this.form, 'port', '1883');
        this.$set(this.form, 'topic', 'up/' + this.form.code);
        this.$set(this.form, 'clientId', '');
      } else {
        this.$set(this.form, 'ip', null);
        this.$set(this.form, 'port', null);
        this.$set(this.form, 'username', null);
        this.$set(this.form, 'password', null);
        this.$set(this.form, 'topic', null);
        this.$set(this.form, 'clientId', null);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.action-button {
  background-color: #004A8D;
  border-color: #004A8D;
  color: #fff;
}
</style>
